package com.unnous.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * unnous
 * 2018/09/30
 */
@EnableWebSecurity
public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DefaultUserDetailsService userService;

    /**
     * 匹配 "/" 路径，不需要权限即可访问
     * 匹配 "/user" 及其以下所有路径，都需要 "USER" 权限
     * 登录地址为 "/login"，登录成功默认跳转到页面 "/user"
     * 退出登录的地址为 "/logout"，退出成功后跳转到页面 "/login"
     * 默认启用 CSRF
     */
    protected void configure(HttpSecurity http) throws Exception{
        http
                .csrf().disable()
                .authorizeRequests()
//                .anyRequest().authenticated()//所有请求必须登陆后才能访问
                .antMatchers("/").permitAll()
                .antMatchers("/user/**","/look/").hasRole("USER")
                .antMatchers("/common/").hasAnyRole("USER","ADMIN")
                .and()
                    .formLogin().loginPage("/login").defaultSuccessUrl("/user")
                    .failureUrl("/login:error")
                    .permitAll()//登陆界面错误界面可以直接访问
                .and()
                    .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                .and()
                    // 使用remember_me 功能 通过cookie校验
                    .rememberMe()
                    .key("unique-and-secret")
                    // cookie 名称
                    .rememberMeCookieName("remember-me-cookie-name")
                    .tokenValiditySeconds(24 * 60 * 60);;
    }

    /**
     * 添加 UserDetailsService， 实现自定义登录校验
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(userService)
                .passwordEncoder(passwordEncoder());
    }
    /**
     * 密码加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
